package crmdna.gspreadsheet;

import java.util.List;
import java.util.Map;

import javax.inject.Named;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.Nullable;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;

import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;

@Api(name = "spreadsheet")
public class GSpreadSheetApi {

	public APIResponse getPublishedSpreadsheetContents(
			@Named("spreadSheetKey") String gsKey,
			@Nullable @Named("maxLinesDefault2500") Integer maxLines) {

		try {
			if (maxLines == null)
				maxLines = 2500;

			List<Map<String, String>> listOfMap = GSpreadSheet
					.getPublishedSpreasheetAsListOfMap(gsKey, maxLines);

			return new APIResponse(Status.SUCCESS, listOfMap);

		} catch (Exception ex) {
			if ((ex instanceof JsonParseException)
					|| (ex instanceof JsonSyntaxException)) {

				APIResponse apiResponse = new APIResponse();
				apiResponse.userFriendlyMessage = "Please check if your spread sheet key is valid and the spreadsheet is published";
				apiResponse.statusCode = Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED;
				return apiResponse;
			}

			return new APIResponse(ex);
		}
	}
}
